package com.blb.demo;

/**
 * 线程交替输出
 */
public class PrintNumDemo {

    public synchronized void printZero(){
        for (int i = 0; i < 10; i++) {
            System.out.print("0 ");
            //通知另一个线程，执行
            this.notify();
            //当前线程等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void printOne(){
        for (int i = 0; i < 10; i++) {
            System.out.print("1 ");
            //通知另一个线程，执行
            this.notify();
            //当前线程等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void gameOver(){
        this.notifyAll();
    }

    public static void main(String[] args) throws InterruptedException {
        PrintNumDemo demo = new PrintNumDemo();
        new Thread(() -> {
            demo.printZero();
        }).start();
        new Thread(() -> {
            demo.printOne();
        }).start();
        Thread.sleep(1000);
        demo.gameOver();
    }
}
